package drds.plus.executor.command_handler;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.abstract_syntax_tree.configuration.TableMetaData;
import drds.plus.sql_process.abstract_syntax_tree.execute_plan.dml.IPut;
import drds.plus.sql_process.abstract_syntax_tree.execute_plan.query.QueryWithIndex;
import drds.plus.sql_process.optimizer.OptimizerContext;

public abstract class CommonCommandHandler implements CommandHandler {

    public CommonCommandHandler() {
        super();
    }

    protected TableMetaData getTableMeta(String tableName) {
        TableMetaData tableMetaData = OptimizerContext.getOptimizerContext().getSchemaManager().getTableMetaData(tableName);
        return tableMetaData;
    }

    protected void prepareTableAndIndexMetaDataForPut(ExecuteContext executeContext, IPut put, TableWithIndexMetaData tableWithIndexMetaData) throws RuntimeException {
        String indexName = put.getIndexName();
        String dataNodeId = put.getDataNodeId();
        prepareTableAndIndexMetaData(executeContext, dataNodeId, indexName, tableWithIndexMetaData);
    }

    protected void prepareTableAndIndexMetaDataForQuery(ExecuteContext executeContext, QueryWithIndex queryWithIndex, TableWithIndexMetaData tableWithIndexMetaData) throws RuntimeException {
        String indexName = queryWithIndex.getIndexName();
        String dataNodeId = queryWithIndex.getDataNodeId();
        prepareTableAndIndexMetaData(executeContext, dataNodeId, indexName, tableWithIndexMetaData);
    }

    /**
     * 准备indexMeta和ITable信息
     */
    protected void prepareTableAndIndexMetaData(ExecuteContext executeContext, String dataNodeId, String indexName, TableWithIndexMetaData tableWithIndexMetaData) throws RuntimeException {
        if (indexName != null && !"".equals(indexName)) {
            String tableName = Utils.getTableName(indexName);
            TableMetaData tableMetaData = getTableMeta(tableName);
            tableWithIndexMetaData.indexMapping = tableMetaData.getIndexMetaData(indexName);
            tableWithIndexMetaData.table = executeContext.getRepository().getTable(dataNodeId, tableMetaData);
        }
    }

}
